const request = require("superagent");
const cheerio = require("cheerio");
const fs = require("fs-extra");
const colors = require("colors");
const { sleep, random } = require("./utils");
const UA =
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36";

/**
 * 打开 html 链接获取大图的 URL
 */
 async function getImgUrl(link) {
  const res = await request.get(link);
  const $ = cheerio.load(res.text);
  await sleep(random(1000, 5000));
  return $("#showimg").find("img").attr("src");
}

// 下载图片
async function download(dir, url, filename) {
  const outputDir = `${dir}/${filename}`
  // pipe() 不能与 Promise(或 callback) 同时使用
  const res = request
    .get(url)
    .set({ Referer: "https://www.3gbizhi.com/", "User-Agent": UA });
  res.pipe(fs.createWriteStream(outputDir));
  console.log(colors.green(`下载背景图完成 => ${filename} => ${url}`));
  await sleep(random(1000, 5000));
  return outputDir
}

async function bg_spider(link, dir) {
  const url = await getImgUrl(link)
  return await download(dir, url, 'bg.jpg')
}

module.exports = bg_spider
